package au.edu.utas.yu_qiao_group.luckyman.ui.draws;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import au.edu.utas.yu_qiao_group.luckyman.MainActivity;
import au.edu.utas.yu_qiao_group.luckyman.R;
import au.edu.utas.yu_qiao_group.luckyman.db.draws.DrawDTO;
import au.edu.utas.yu_qiao_group.luckyman.db.draws.DrawListDTO;
import au.edu.utas.yu_qiao_group.luckyman.db.tickets.TicketDTO;
import au.edu.utas.yu_qiao_group.luckyman.service.DrawService;
import au.edu.utas.yu_qiao_group.luckyman.ui.components.SwipeRecyclerView;

public class DrawsFragment extends Fragment {

  private static final String TAG = "DrawingList";
  private ArrayList<DrawListDTO> mDataset;
  private List<DrawListDTO> mFilteredDataset;

  private SwipeRecyclerView mRecyclerView;
  private SwipeRecyclerView.Adapter mAdapter;
  protected SwipeRecyclerView.LayoutManager mLayoutManager;
  private int mCurrentFilterStatus = DrawDTO.STATUS_PENDING;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initDataset();
//        mTargetRaffleVm = new ViewModelProvider(getActivity()).get(SharedRaffleViewModel.class);
  }

  @Override
  public View onCreateView(@NonNull LayoutInflater inflater,
                           ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_draws, container, false);
    rootView.setTag(TAG);
    initRecyclerView(rootView);
    setTabListener(rootView);
    System.out.println("onCreateView");
    return rootView;
  }

  public void initRecyclerView(final View rootView) {
    mRecyclerView = rootView.findViewById(R.id.draw_list);

    mLayoutManager = new LinearLayoutManager(getActivity());

    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.scrollToPosition(0);
    mAdapter = new DrawListViewItemAdapter(mFilteredDataset, onStartBtnClick, onCancelBtnClick);
    mRecyclerView.setAdapter(mAdapter);
  }

  private View.OnClickListener onStartBtnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      DrawListDTO d = mFilteredDataset.get(Integer.parseInt(v.getTag().toString()));
      switch (d.getMStatus()) {
        case DrawDTO.STATUS_PENDING:
          MainActivity activity = (MainActivity) getActivity();
          final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          final EditText edit = new EditText(getContext());
          if (d.getMDrawMethod() == 0) {
            dialog.setMessage("Are you sure to draw a NORMAL raffle? Winner No will be generated between sold ticket NOs");
          } else {
            dialog.setMessage("Are you sure to draw a MARGIN raffle? Please enter the margin number (0 - 999), ticketNo 1000 wins if no margin");
            dialog.setView(edit);
          }
          dialog.setPositiveButton("Draw!", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              if (d.getMDrawMethod() == 1 && TextUtils.isEmpty(edit.getText().toString())) {
                Toast.makeText(getContext(), "please enter margin!", Toast.LENGTH_SHORT).show();
                return;
              }
              DrawListDTO updatedDraw = null;
              try {
                updatedDraw = d.getMDrawMethod() == 0
                  ? DrawService.runDraw(activity.mDb, d)
                  : DrawService.runDraw(activity.mDb, d, edit.getText().toString());
                popupWinner(updatedDraw.getMWinnerTicketNo(), updatedDraw.getMWinnerPhone());
                refreshDataset();
              } catch (Exception e) {
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
              }
            }
          });
          dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              dialog.cancel();
            }
          });
          dialog.show();
          break;
        case DrawDTO.STATUS_FINISHED:
          popupWinner(d.getMWinnerTicketNo(), d.getMWinnerPhone());
          break;
        default:
          Toast.makeText(getContext(), d.getMRaffleName() + " has been cancelled", Toast.LENGTH_SHORT).show();
      }
    }
  };

  private void popupWinner(String ticketNo, @Nullable String phone) {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
    alertDialog.setMessage("JackPot Ticket NO. is " + ticketNo + "! "
            + (phone == null ? "NO WINNER for this round." : "Congratulations to Customer " + phone));
    alertDialog.show();
  }

  private View.OnClickListener onCancelBtnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
      dialog.setMessage("please double confirm your dangerous CANCEL action");
      dialog.setPositiveButton("I am sure", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          DrawListDTO targetDTO = mFilteredDataset.get((Integer) v.getTag());
          MainActivity activity = (MainActivity) getActivity();
          if (DrawService.cancelDraw(activity.mDb, targetDTO)) {
            refreshDataset();
            Toast.makeText(getContext(), "cancelled " + targetDTO.getMRaffleName() + " draw", Toast.LENGTH_SHORT).show();
          } else {
            Toast.makeText(getContext(), targetDTO.getMRaffleName() + " failed to cancel!", Toast.LENGTH_SHORT).show();
          }
        }
      });
      dialog.show();
    }
  };

  @Override
  public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
  }

  private void initDataset() {
    MainActivity activity = (MainActivity) getActivity();
    mDataset = DrawService.retrieveAll(activity.mDb);
    updateFilteredDataset();
  }

  private void updateFilteredDataset() {
    mFilteredDataset = mDataset.stream().filter(i -> i.getMStatus() == mCurrentFilterStatus)
            .collect(Collectors.toList());
  }

  private void refreshDataset() {
    MainActivity activity = (MainActivity) getActivity();
    ArrayList<DrawListDTO> updatedDataset = DrawService.retrieveAll(activity.mDb);
    mDataset.clear();
    mDataset.addAll(updatedDataset);
    updateFilteredDataset();
    mRecyclerView.setAdapter(new DrawListViewItemAdapter(mFilteredDataset, onStartBtnClick, onCancelBtnClick));
  }

  private void setTabListener(View rootView) {
    TabLayout t = rootView.findViewById(R.id.draw_tab);
    t.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
      @Override
      public void onTabSelected(TabLayout.Tab tab) {
        // notice: position is designed to be fit to their status value;
        mCurrentFilterStatus = tab.getPosition();
        updateFilteredDataset();
        mRecyclerView.setAdapter(new DrawListViewItemAdapter(mFilteredDataset, onStartBtnClick, onCancelBtnClick));
      }

      @Override
      public void onTabUnselected(TabLayout.Tab tab) {

      }

      @Override
      public void onTabReselected(TabLayout.Tab tab) {

      }
    });
  }
}
